#!/usr/local/bin/perl -w
use strict;

use EV;
use IO::Socket::INET;
use Time::HiRes qw(gettimeofday);

my @all;
my %tmp;
my $tmp = 0;
my $g;

my $addr = "127.0.0.1";
my $port = 8010;

run();
sub run {
	if($g = make()){
		EV::loop;
	}
}
sub make {
	my $s = IO::Socket::INET->new(
		LocalAddr => $addr,
		LocalPort => $port,
		Listen => 100,
		ReuseAddr => 1,
	);
	unless($s){
		return 0;
	}
	
	return EV::io $s,EV::READ,\&can_stream;
}

sub can_stream {
	my ($w) = @_;
	my $ns = $w->fh->accept;
	my $nw = EV::io $ns, EV::READ,\&can_read;
	$nw->data(scalar @all);
	push @all, $nw;
#	print "accept from ",$ns->peerhost,"\n";
}
sub can_read {
	my ($w) = @_;
	my $buf;
	$w->fh->recv($buf,1024);
#	print "readed '$buf'\n";
	if($buf){
		resend();
	}else{
		$all[$w->data] = undef;
	}
}
sub resend {
	my $l = @all;
	for my $w (@all){
		my $nw = EV::io $w->fh,EV::WRITE,\&can_write;
		$tmp{$tmp} = $nw;
		$nw->data([$l."\n",$tmp++]);
	}
}
sub can_write {
	my ($w) = @_;
	my $need = length($w->data->[0]);
	my $r = $w->fh->send($w->data->[0]);
#	print "send\n";
	if($r){
		if($r < $need){
			substr($w->data->[0],0,$r,"");
		}else{
			$w->data->[0] = "";
			delete $tmp{$w->data->[1]};
		}
	}else{
		delete $tmp{$w->data->[1]};
	}
}

